package com.sunfeng.netty.atguigu2.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 完成文件复制使用一个ByteBuffer
 *
 * @author sunfeng
 * @date 2021/03/22 16:44
 **/
public class NIOFileChannel03 {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("1.txt");

        FileChannel inputStreamChannel = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");

        FileChannel outputStreamChannel = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true){
            // 重置关联属性       不加这个read会一直为0
            byteBuffer.clear();
            int read = inputStreamChannel.read(byteBuffer);
            System.out.println(read);
            if(read==-1){
                break;
            }
            byteBuffer.flip();
            outputStreamChannel.write(byteBuffer);
        }
        int len=0;
        while ((len=inputStreamChannel.read(byteBuffer))!=-1){
            byteBuffer.flip();
            outputStreamChannel.write(byteBuffer);
            byteBuffer.clear();
        }

        fileInputStream.close();
        fileOutputStream.close();

    }

}
